/*
 * Copyright 2008-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ssn.servicearea.web;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import ssn.common.web.CommonController;
import ssn.servicearea.service.ServiceAreaService;
import ssn.servicearea.vo.ServiceAreaVO;
import egovframework.rte.fdl.cmmn.exception.EgovBizException;
import egovframework.rte.fdl.string.EgovStringUtil;


/**  
 * @Class Name : 
 * @Description : 
 * @Modification Information  
 * @
 * @  수정일      수정자              수정내용
 * @ ---------   ---------   -------------------------------
 * @ 2013.10.09           최초생성
 * 
 * @since 2013. 09.30
 * @version 1.0
 * @see
 */
@SuppressWarnings("rawtypes")
@Controller
public class ServiceAreaController extends CommonController{
	
    @Resource(name = "serviceareaService")
    private ServiceAreaService serviceareaService;
    
    /**
	 * 글 목록을 조회한다. 
	 * @param 
	 * @param model
	 * @return 
	 * @exception Exception
	 */
    @RequestMapping(value="/servicearea/serviceareaList.do")
    public String serviceareaList(@ModelAttribute("serviceareaVO") ServiceAreaVO serviceareaVO,
    			ModelMap model) throws Exception {
    	
    	/** pageUnit : 페이지 리스트 개수, pageSize : 페이징 개수
    	serviceareaVO.setPageUnit(15);
    	serviceareaVO.setPageSize(15);
    	*/
    	if(!loginSessionInfo.get().isAdmin()){
    		serviceareaVO.setSearchServiceArea(loginSessionInfo.get().getSsa_area_key());
    	}
    	Map resultMap = serviceareaService.selectServiceAreaList(serviceareaVO);
    	List resultList = (List)resultMap.get("resultList");
    	serviceareaVO.setTotalRecordCount((Integer)resultMap.get("resultListCnt"));
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("zoneList", resultMap.get("zoneList"));
    	model.addAttribute("serviceareaVO", serviceareaVO);
        
        return "/servicearea/serviceareaList";
    }
    
    /**
     * 뷰페이지
     * @param serviceareaVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/servicearea/serviceareaView.do")
    public String serviceareaView(@ModelAttribute("serviceareaVO") ServiceAreaVO serviceareaVO,
    			ModelMap model) throws Exception {
    	if(EgovStringUtil.isEmpty(serviceareaVO.getSsa_area_key())){
    		throw new EgovBizException(propertiesService.getString("info.nodata.msg"));
    	}
    	ServiceAreaVO resultVO = serviceareaService.selectServiceAreaInfo(serviceareaVO);
    	if(resultVO != null){
    		resultVO.setSearchParam(serviceareaVO);
    	}
    	
    	model.addAttribute("resultVO", resultVO);
        return "/servicearea/serviceareaView";
    }
    
    /**
     * 글쓰기 수정폼
     * @param serviceareaVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/servicearea/serviceareaWriteForm.do")
    public String serviceareaWriteForm(@ModelAttribute("serviceareaVO") ServiceAreaVO serviceareaVO,
    			ModelMap model) throws Exception {
    	if(!loginSessionInfo.get().isAdmin()){
    		serviceareaVO.setSsa_area_key(loginSessionInfo.get().getSsa_area_key());
    	}
    	if(EgovStringUtil.isNotEmpty(serviceareaVO.getSsa_area_key())){
    		ServiceAreaVO resultVO = serviceareaService.selectServiceAreaInfo(serviceareaVO);
    		if(resultVO != null){
        		resultVO.setSearchParam(serviceareaVO);
        	}
    		model.addAttribute("resultVO", resultVO);
    	}else{
    		model.addAttribute("resultVO", serviceareaVO);
    	}
    	Map resultOtherInfo = serviceareaService.selectServiceAreaOtherInfo();
    	model.addAttribute("zoneList", resultOtherInfo.get("zoneList"));
    	model.addAttribute("userList", resultOtherInfo.get("userList"));
        return "/servicearea/serviceareaWriteForm";
    }
    
    @RequestMapping(value="/servicearea/serviceareaSave.do", method=RequestMethod.GET)
    public String serviceareaWriteFormGet(ModelMap model) throws Exception {
    	return "redirect:/servicearea/serviceareaWriteForm.do";
    }
    
    /**
     * 저장/수정
     * @param serviceareaVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/servicearea/serviceareaSave.do", method=RequestMethod.POST)
    public String serviceareaSave(@ModelAttribute("serviceareaVO") @Valid ServiceAreaVO serviceareaVO, 
    		BindingResult bindingResult, RedirectAttributes redirectAttr) throws Exception {
    	String returnUrl = "/servicearea/serviceareaView.do";
    	if(bindingResult.hasErrors()){
    		for(FieldError error :  bindingResult.getFieldErrors()){
    			redirectAttr.addFlashAttribute("error_"+error.getField(), error.getDefaultMessage());
    		}
    		Map resultOtherInfo = serviceareaService.selectServiceAreaOtherInfo();
    		redirectAttr.addFlashAttribute("zoneList", resultOtherInfo.get("zoneList"));
    		redirectAttr.addFlashAttribute("userList", resultOtherInfo.get("userList"));
    		redirectAttr.addFlashAttribute("serviceareaVO", serviceareaVO);
			return "redirect:/servicearea/serviceareaWriteForm.do";
    	}
    	if(EgovStringUtil.isNotEmpty(serviceareaVO.getSsa_area_key())){
    		serviceareaService.updateServiceAreaInfo(serviceareaVO);
    	}else{
    		UUID uuid = UUID.randomUUID();
    		serviceareaVO.setSsa_area_key(uuid.toString());
    		serviceareaService.insertServiceAreaInfo(serviceareaVO);
    	}
    	if(!loginSessionInfo.get().isAdmin()){
    		returnUrl = "/login/loginForm.do";
    		redirectAttr.addFlashAttribute("msg", "수정 되었습니다. \\n다시 로그인 해주십시요.");
    	}else{
    		redirectAttr.addAttribute("ssa_area_key", serviceareaVO.getSsa_area_key());
    		redirectAttr.addAttribute("pageIndex", serviceareaVO.getPageIndex());
    	}
    	return "redirect:"+returnUrl;
    } 
    
    /**
	 * 관리자 목록을 조회한다. 
	 * @param 
	 * @param model
	 * @return 
	 * @exception Exception
	 */
    @RequestMapping(value="/servicearea/adminUserList.do")
    public String adminUserList(@ModelAttribute("serviceareaVO") ServiceAreaVO serviceareaVO,
    			ModelMap model) throws Exception {
    	
    	Map resultMap = serviceareaService.selectServiceAreaAdminList(serviceareaVO);
    	List resultList = (List)resultMap.get("resultList");
    	serviceareaVO.setTotalRecordCount((Integer)resultMap.get("resultListCnt"));
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("serviceareaVO", serviceareaVO);
        
        return "/servicearea/adminUserList";
    }
    
    /**
     * 관리자 뷰페이지
     * @param serviceareaVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/servicearea/adminUserView.do")
    public String adminUserView(@ModelAttribute("serviceareaVO") ServiceAreaVO serviceareaVO,
    			ModelMap model) throws Exception {
    	
    	if(EgovStringUtil.isEmpty(serviceareaVO.getSsa_area_key())){
    		throw new EgovBizException(propertiesService.getString("info.nodata.msg"));
    	}
    	ServiceAreaVO resultVO = serviceareaService.selectServiceAreaAdminInfo(serviceareaVO);
    	if(resultVO != null){
    		resultVO.setSearchParam(serviceareaVO);
    	}
    	model.addAttribute("resultVO", resultVO);
        return "/servicearea/adminUserView";
    }
    
    /**
     * 관리자 수정폼
     * @param serviceareaVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/servicearea/adminUserWriteForm.do")
    public String adminUserWriteForm(@ModelAttribute("serviceareaVO") ServiceAreaVO serviceareaVO,
    			ModelMap model) throws Exception {
    	if(EgovStringUtil.isNotEmpty(serviceareaVO.getSsa_area_key())){
    		ServiceAreaVO resultVO = serviceareaService.selectServiceAreaAdminInfo(serviceareaVO);
    		if(resultVO != null){
        		resultVO.setSearchParam(serviceareaVO);
        	}
    		model.addAttribute("resultVO", resultVO);
    	}else{
    		model.addAttribute("resultVO", serviceareaVO);
    	}
        return "/servicearea/adminUserWriteForm";
    }
    
    @RequestMapping(value="/servicearea/adminUserSave.do", method=RequestMethod.GET)
    public String adminUserWriteFormGet(ModelMap model) throws Exception {
    	return "redirect:/servicearea/adminUserWriteForm.do";
    }
    
    /**
     * 관리자 저장/수정
     * @param serviceareaVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/servicearea/adminUserSave.do", method=RequestMethod.POST)
    public ModelAndView adminUserSave(@ModelAttribute("serviceareaVO") ServiceAreaVO serviceareaVO) throws Exception {
    	ModelAndView mav = new ModelAndView();
    	mav.setView(new RedirectView(servletContext.getContextPath()+"/servicearea/adminUserView.do"));
    	if(EgovStringUtil.isNotEmpty(serviceareaVO.getSsa_area_key())){
    		serviceareaService.updateServiceAreaAdminInfo(serviceareaVO);
    	}else{
    		UUID uuid = UUID.randomUUID();
    		serviceareaVO.setSsa_area_key(uuid.toString());
    		serviceareaService.insertServiceAreaAdminInfo(serviceareaVO);
    	}
    	mav.addObject("ssa_area_key", serviceareaVO.getSsa_area_key());
    	mav.addObject("pageIndex", serviceareaVO.getPageIndex());
    	return mav;
    } 
}
